import uuid
from datetime import datetime
from typing import Optional
from app.utils.mysql_helper import MySQLHelper
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class TranslationLog:
    """
    翻译日志模型
    用于记录翻译操作的详细信息，包括源语言、目标语言、翻译文本、积分消耗等
    """
    
    def __init__(self, auto_commit=False):
        """
        初始化翻译日志模型
        """
        self.db_helper = MySQLHelper(auto_commit=auto_commit)
        self._ensure_table_exists()
    
    def _ensure_table_exists(self):
        """
        确保翻译日志表存在
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute("""
                CREATE TABLE IF NOT EXISTS translation_logs (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    log_id VARCHAR(36) NOT NULL,
                    shop_domain VARCHAR(255) NOT NULL,
                    source_text TEXT NOT NULL,
                    translated_text TEXT,
                    source_language VARCHAR(50) NOT NULL,
                    target_language VARCHAR(50) NOT NULL,
                    text_length INT NOT NULL,
                    points_consumed INT DEFAULT 0,
                    status ENUM('SUCCESS', 'FAILED', 'PENDING') NOT NULL DEFAULT 'PENDING',
                    error_message VARCHAR(500),
                    metadata_modle VARCHAR(255),
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_shop_domain (shop_domain),
                    INDEX idx_log_id (log_id),
                    INDEX idx_created_at (created_at)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                """)
            conn.commit()
        except Exception as e:
            logging.error(f"创建翻译日志表失败: {e}")
            if conn:
                conn.rollback()
            raise
    
    def create_log(self, shop_domain: str, source_text: str, source_language: str,
                  target_language: str, text_length: int, metadata_model: str = "") -> str:
        """
        创建翻译日志记录
        
        Args:
            shop_domain: 店铺域名
            source_text: 源文本
            source_language: 源语言
            target_language: 目标语言
            text_length: 文本长度
            metadata_modle: 元数据模块
            
        Returns:
            str: 日志ID
        """
        try:
            log_id = str(uuid.uuid4())
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute("""
                INSERT INTO translation_logs 
                (log_id, shop_domain, source_text, source_language, target_language, 
                 text_length, status, metadata_modle)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (log_id, shop_domain, source_text, source_language, target_language,
                 text_length, 'PENDING', metadata_model))
            conn.commit()
            return log_id
        except Exception as e:
            logging.error(f"创建翻译日志失败: {e}")
            if conn:
                conn.rollback()
            raise
    
    def update_log(self, log_id: str, translated_text: Optional[str] = None,
                  points_consumed: Optional[int] = None, status: Optional[str] = None,
                  error_message: Optional[str] = None) -> bool:
        """
        更新翻译日志记录
        
        Args:
            log_id: 日志ID
            translated_text: 翻译后的文本
            points_consumed: 消耗的积分
            status: 状态
            error_message: 错误信息
            
        Returns:
            bool: 是否更新成功
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                # 构建更新语句
                update_fields = []
                params = []
                
                if translated_text is not None:
                    update_fields.append("translated_text = %s")
                    params.append(translated_text)
                if points_consumed is not None:
                    update_fields.append("points_consumed = %s")
                    params.append(points_consumed)
                if status is not None:
                    update_fields.append("status = %s")
                    params.append(status)
                if error_message is not None:
                    update_fields.append("error_message = %s")
                    params.append(error_message)
                
                # 添加WHERE条件
                params.append(log_id)
                
                # 执行更新
                cursor.execute(
                    f"UPDATE translation_logs SET {', '.join(update_fields)} WHERE log_id = %s",
                    params
                )
            conn.commit()
            return cursor.rowcount > 0
        except Exception as e:
            logging.error(f"更新翻译日志失败: {e}")
            if conn:
                conn.rollback()
            raise
    
    def get_log_by_id(self, log_id: str) -> dict:
        """
        根据日志ID获取翻译日志
        
        Args:
            log_id: 日志ID
            
        Returns:
            dict: 日志记录
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute(
                    "SELECT * FROM translation_logs WHERE log_id = %s",
                    (log_id,)
                )
                return cursor.fetchone()
        except Exception as e:
            logging.error(f"获取翻译日志失败: {e}")
            raise
    
    def get_shop_translation_history(self, shop_domain: str, limit: int = 50, 
                                   offset: int = 0) -> list:
        """
        获取店铺的翻译历史记录
        
        Args:
            shop_domain: 店铺域名
            limit: 返回记录数量限制
            offset: 偏移量
            
        Returns:
            list: 翻译历史记录列表
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute(
                    """
                    SELECT log_id, source_text, translated_text, source_language, 
                           target_language, text_length, points_consumed, status, 
                           created_at
                    FROM translation_logs
                    WHERE shop_domain = %s
                    ORDER BY created_at DESC
                    LIMIT %s OFFSET %s
                    """,
                    (shop_domain, limit, offset)
                )
                return cursor.fetchall()
        except Exception as e:
            logging.error(f"获取翻译历史失败: {e}")
            raise

# 创建模型实例
translation_log_model = TranslationLog()